home *** CD-ROM | disk | FTP | other *** search
- Path: waichung.demon.co.uk!kyn
- From: Kyn Wai Chung <kyn@waichung.demon.co.uk>
- Newsgroups: comp.lang.c++
- Subject: help required on binary trees
- Date: Wed, 13 Mar 1996 20:53:34 +0000
- Organization: a
- Distribution: world
- Message-ID: <ByDMSCAOXzRxEwnw@waichung.demon.co.uk>
- NNTP-Posting-Host: waichung.demon.co.uk
- X-NNTP-Posting-Host: waichung.demon.co.uk
- MIME-Version: 1.0
- X-Newsreader: Turnpike Version 1.10 <gzdqIUQAgGCVFgCv6c5ZSzseKJ>
-
- I require help in constructing a binary search tree in c++, as i am
- relatively new to the language i am not sure how to go about
- implementing
- it.
- Do i construct a class called btree or do i use the following:-
-
- struct node
- {
- data d;
- struct node *left;
- struct node *right;
- }
-
- if this is correct how do build a tree from this and insert words into
- it?
- The following is how i would implement a binary search tree in pascal.
- Your help will be much appreciated.
-
- procedure BuildTree;
- begin
- Root := nil;
- while not eof do
- begin
- read(NewKey);
- searchAndInsert(NewKey, {starting at} Root)
- end
- end {BuildTree}
-
-
- procedure SearchAndInsert(NewKey : integer; {in} var Subtree : Pointer);
- begin
- if Subtree = nil then
- begin
- new(SubTree);
- with SubTree^ do
- begin
- Key := NewKey;
- Left := nil;
- Right := nil
- end {with}
- end {then statement}
- else
- begin
- if NewKey < SubTree^.Key then
- SearchAndInsert(NewKey; {in} SubTree^.Left)
- elseif NewKey > SubTree^.Key then
- SearchAndInsert(NewKey; {in} SubTree^.Right)
- else
- writeln(NewKey, ' is a duplicate entry.')
- end
- end {SearchAndInsert}
-
-
- procedure PrintTree(Subtree : Pointer);
- begin
- if Subtree <> nil then
- with Subtree do
- begin
- PrintTree(Left);
- writeln(Key);
- PrintTree(Right)
- end
- end {PrintTree}
-
- --
- Kyn Wai Chung
-